package com.practice.Java中HttpClient如何使用;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.Optional;

/**
 * @program: tenghw-practice-demo
 * @author: tenghw
 * @create: 2023-12-24 14:40
 * @Version 1.0
 * @description: 使用Apache HttpClient在Java 8中发送GET和POST请求的基本示例：
 **/
public class ApacheHttpClientDemo {
    //get请求
    public static void main0(String[] args) throws IOException {
        // 创建一个Http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 请求的url
        String url = "http://www.baidu.com";
        // 创建一个HttpGet请求
        HttpGet httpGet = new HttpGet(url);
        // 执行请求
        try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet);){
         // 响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("响应状态码:"+statusCode);//200
            // 响应正文
            HttpEntity entity = httpResponse.getEntity();
            //if(null!=entity){
            //    System.out.println("响应正文:"+ EntityUtils.toString(entity));
            //}
            System.out.println("响应正文:"+ Optional.ofNullable(String.valueOf(entity)).orElse("无任何响应内容"));
        }
    }
    //post请求(包含JSON数据)
    public static void main(String[] args) throws IOException {
        // 创建一个Http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 请求的url
        String url = "http://www.baidu.com";
        // 创建一个HttpPost请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/json");
        // 设置请求体
        String requestBody="{\"name\":\"韩信\",\"朝代\":\"汉朝\"}";
        httpPost.setEntity(new StringEntity(requestBody,"UTF-8"));

        // 发送请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        try {
            // 响应状态码
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("响应状态码:"+statusCode);//200
            // 响应正文
            HttpEntity entity = httpResponse.getEntity();
            System.out.println("响应正文:"+ Optional.ofNullable(EntityUtils.toString(entity)).orElse("无任何响应内容"));
        }finally {
            httpResponse.close();
        }

    }


}